﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace BaseModel
{
    /// <summary>
    /// 基础树
    /// </summary>
    [Serializable]
    [DataContract]
    public class Tree
    {
        #region 属性

        /// <summary>
        /// 主键标识
        /// </summary>
        [DataMember]
        public int id { get; set; }

        /// <summary>
        /// 父标识
        /// </summary>
        [DataMember]
        public int? pid { get; set; }

        /// <summary>
        /// 显示节点文本
        /// </summary>
        [DataMember]
        public string text { get; set; }

        /// <summary>
        /// 节点状态，'open' 或 'closed'
        /// </summary>
        [DataMember]
        public string state { get; set; }

        /// <summary>
        /// 节点状态，'open' 或 'closed'
        /// </summary>
        [DataMember]
        public Attributes attributes { get; set; }

        /// <summary>
        /// 叶子
        /// </summary>
        [DataMember]
        public bool leaf { get; set; }

        /// <summary>
        /// 层次
        /// </summary>
        [DataMember]
        public string levels { get; set; }

        /// <summary>
        /// 节点状态，'open' 或 'closed'
        /// </summary>
        [DataMember]
        public List<Tree> children { get; set; }

        #endregion

        #region GetTree  

        /// <summary>
        /// 递归树
        /// </summary>
        /// <param name="id">开始ID</param>
        /// <param name="entity">list列表</param>
        /// <param name="first">是否是第一次递归</param>
        /// <returns></returns>
        public static List<Tree> GetTree(int id, List<Tree> entity, bool first = false)
        {
            var tempEntity = entity;
            if (first)
            {
                tempEntity = tempEntity.Where(ex => ex.id == id).ToList();
            }
            else if (id >0)
            {
                tempEntity = tempEntity.Where(ex => ex.pid == id).ToList();
            }
            else
            {
                tempEntity = tempEntity.Where(ex => ex.pid.Value == 0).ToList();
            }
            var temp = tempEntity.OrderBy(ex => ex.levels).ToList();


            List<Tree> list = new List<Tree>();
            foreach (var ex in temp)
            {
                if (ex.leaf == false)
                {
                    var objects = GetTree(ex.id, entity);

                    var obj = ex;
                    obj.children = objects;
                    list.Add(obj);
                }
                else
                {
                    list.Add(ex);
                }
            }
            return list;
        }
        #endregion GetTree
    }
}
